package com.hzdracom.zhangnn.mainfestdemo;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private TextView tvSDCard;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvSDCard = (TextView) findViewById(R.id.sdcard);

        tvSDCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                checkSDCard();
                showPermission();
            }
        });
    }


    private void showPermission(){
      boolean b=  ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if(b){
            checkSDCard();
        }else{
            Toast.makeText(this,"request permission is not should",Toast.LENGTH_SHORT).show();
        }
    }


    private void checkSDCard() {
       int i= ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if(i== PackageManager.PERMISSION_GRANTED){
            Toast.makeText(this,"已经授权",Toast.LENGTH_SHORT).show();
        }else if(i==PackageManager.PERMISSION_DENIED){
            requestSDCard();
        }
    }

    private void requestSDCard() {
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},101);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
       if(requestCode==101){
          if( grantResults[0]==0){
              Toast.makeText(this,"授权成功",Toast.LENGTH_SHORT).show();
          }else if (grantResults[0]==-1){
              Toast.makeText(this,"授权失败",Toast.LENGTH_SHORT).show();
          }else {
              Toast.makeText(this,"操作失败",Toast.LENGTH_SHORT).show();
          }
       }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
